/**
 * @deprecated 此WebSocket服务已废弃，请使用 unified-websocket.ts
 * WebSocket服务管理类
 * 统一管理WebSocket连接、消息收发、心跳及重连机制
 *
 * 迁移指南:
 * import { wsManager } from '@/services/websocket'
 * 改为:
 * import { unifiedWebSocketService } from '@/services/unified-websocket'
 */

// 数据解析规则配置
export interface DataParsingRule {
  // 数据提取路径配置
  dataPath?: string; // JSONPath或dot notation, 如: "data", "payload.values", "$.data"
  // 数据点提取规则
  pointExtraction: 'auto' | 'manual' | 'custom';
  // 自动提取时的排除字段
  excludeFields?: string[];
  // 手动指定字段映射
  fieldMappings?: Array<{
    sourcePath: string; // 源字段路径
    pointId: string; // 数据点ID
  }>;
  // 自定义解析函数 (JavaScript代码字符串)
  customParser?: string;
}

export interface DataSource {
  id: string;
  name: string;
  url: string;
  enabled: boolean;
  description?: string;
  // 新增：数据解析配置
  parsingRule?: DataParsingRule;
}

export interface WSMessage {
  type: string;
  data: any;
  timestamp?: number;
  source?: string;
}

export interface WSConnection {
  id: string;
  name: string;
  url: string;
  ws: WebSocket | null;
  status: 'disconnected' | 'connecting' | 'connected' | 'error';
  lastHeartbeat: number;
  reconnectAttempts: number;
  reconnectTimer: number | null;
  heartbeatTimer: number | null;
  // 新增消息统计
  messagesSent: number;
  messagesReceived: number;
  bytesReceived: number;
}

export class WebSocketManager {
  private connections: Map<string, WSConnection> = new Map();
  private messageHandlers: Map<string, (message: WSMessage) => void> = new Map();
  private globalMessageHandler: ((message: WSMessage) => void) | null = null;

  // 配置参数
  private readonly config = {
    heartbeatInterval: 30000, // 心跳间隔 30秒
    reconnectInterval: 5000, // 重连间隔 5秒
    maxReconnectAttempts: 10, // 最大重连次数
    connectionTimeout: 10000 // 连接超时 10秒
  };

  constructor() {
    // 页面卸载时关闭所有连接
    window.addEventListener('beforeunload', () => {
      this.disconnectAll();
    });
  }

  /**
   * 验证WebSocket URL格式
   */
  private isValidWebSocketUrl(url: string): boolean {
    if (!url || typeof url !== 'string') {
      return false;
    }

    // 检查协议
    if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
      return false;
    }

    try {
      // 尝试构造URL对象来验证格式
      new URL(url);
      return true;
    } catch (error) {
      return false;
    }
  }

  /**
   * 设置全局消息处理器
   */
  setGlobalMessageHandler(handler: (message: WSMessage) => void) {
    this.globalMessageHandler = handler;
  }

  /**
   * 设置特定数据源的消息处理器
   */
  setMessageHandler(sourceId: string, handler: (message: WSMessage) => void) {
    this.messageHandlers.set(sourceId, handler);
  }

  /**
   * 移除消息处理器
   */
  removeMessageHandler(sourceId: string) {
    this.messageHandlers.delete(sourceId);
  }

  /**
   * 连接到数据源
   */
  async connect(dataSource: DataSource): Promise<boolean> {
    if (this.connections.has(dataSource.id)) {
      console.warn(`Connection ${dataSource.id} already exists`);
      return false;
    }

    // 验证数据源
    if (!dataSource.url || !this.isValidWebSocketUrl(dataSource.url)) {
      console.error(`Invalid WebSocket URL in dataSource: ${dataSource.url}`);
      return false;
    }

    const connection: WSConnection = {
      id: dataSource.id,
      name: dataSource.name,
      url: dataSource.url,
      ws: null,
      status: 'disconnected',
      lastHeartbeat: Date.now(),
      reconnectAttempts: 0,
      reconnectTimer: null,
      heartbeatTimer: null,
      // 初始化消息统计
      messagesSent: 0,
      messagesReceived: 0,
      bytesReceived: 0
    };

    this.connections.set(dataSource.id, connection);
    return this.doConnect(connection);
  }

  /**
   * 执行连接
   */
  private async doConnect(connection: WSConnection): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        connection.status = 'connecting';

        // 验证WebSocket URL格式
        if (!connection.url || !this.isValidWebSocketUrl(connection.url)) {
          console.error(`Invalid WebSocket URL: ${connection.url}`);
          connection.status = 'error';
          resolve(false);
          return;
        }

        const ws = new WebSocket(connection.url);
        connection.ws = ws;

        // 连接超时处理
        const timeoutId = setTimeout(() => {
          if (connection.status === 'connecting') {
            console.error(`Connection timeout: ${connection.url}`);
            ws.close();
            connection.status = 'error';
            this.scheduleReconnect(connection);
            resolve(false);
          }
        }, this.config.connectionTimeout);

        ws.onopen = () => {
          clearTimeout(timeoutId);
          connection.status = 'connected';
          connection.reconnectAttempts = 0;
          connection.lastHeartbeat = Date.now();

          this.startHeartbeat(connection);
          resolve(true);
        };

        ws.onmessage = (event) => {
          this.handleMessage(connection, event);
        };

        ws.onclose = (event) => {
          clearTimeout(timeoutId);
          this.handleClose(connection, event);
        };

        ws.onerror = (event) => {
          clearTimeout(timeoutId);
          console.error(`WebSocket error for ${connection.url}:`, event);
          connection.status = 'error';
          this.scheduleReconnect(connection);
          resolve(false);
        };
      } catch (error) {
        console.error(`Failed to create WebSocket connection: ${connection.url}`, error);
        connection.status = 'error';
        this.scheduleReconnect(connection);
        resolve(false);
      }
    });
  }

  /**
   * 处理接收到的消息
   */
  private handleMessage(connection: WSConnection, event: MessageEvent) {
    try {
      let message: WSMessage;

      // 更新接收统计
      connection.messagesReceived++;
      connection.bytesReceived += new Blob([event.data]).size;

      // 尝试解析JSON消息
      try {
        const data = JSON.parse(event.data);
        message = {
          type: data.type || 'data',
          data: data.data || data,
          timestamp: Date.now(),
          source: connection.id
        };
      } catch {
        // 如果不是JSON，作为普通文本处理
        message = {
          type: 'text',
          data: event.data,
          timestamp: Date.now(),
          source: connection.id
        };
      }

      // 更新心跳时间
      connection.lastHeartbeat = Date.now();

      // 调用特定处理器
      const handler = this.messageHandlers.get(connection.id);
      if (handler) {
        handler(message);
      }

      // 调用全局处理器
      if (this.globalMessageHandler) {
        this.globalMessageHandler(message);
      }
    } catch (error) {
      console.error(`Error handling message from ${connection.url}:`, error);
    }
  }

  /**
   * 处理连接关闭
   */
  private handleClose(connection: WSConnection, event: CloseEvent) {
    this.stopHeartbeat(connection);
    connection.status = 'disconnected';
    connection.ws = null;

    // 如果不是主动关闭，尝试重连
    if (event.code !== 1000) {
      // 1000 = 正常关闭
      this.scheduleReconnect(connection);
    }
  }

  /**
   * 安排重连
   */
  private scheduleReconnect(connection: WSConnection) {
    if (connection.reconnectAttempts >= this.config.maxReconnectAttempts) {
      console.error(`Max reconnect attempts reached for ${connection.url}`);
      connection.status = 'error';
      return;
    }

    if (connection.reconnectTimer) {
      clearTimeout(connection.reconnectTimer);
    }

    connection.reconnectAttempts++;

    connection.reconnectTimer = window.setTimeout(() => {
      if (connection.status !== 'connected') {
        this.doConnect(connection);
      }
    }, this.config.reconnectInterval);
  }

  /**
   * 启动心跳
   */
  private startHeartbeat(connection: WSConnection) {
    this.stopHeartbeat(connection); // 先停止已有的心跳

    connection.heartbeatTimer = window.setInterval(() => {
      if (connection.ws && connection.status === 'connected') {
        // 检查是否长时间没有收到消息
        const timeSinceLastHeartbeat = Date.now() - connection.lastHeartbeat;
        if (timeSinceLastHeartbeat > this.config.heartbeatInterval * 2) {
          console.warn(`No heartbeat from ${connection.url}, reconnecting...`);
          connection.ws.close();
          return;
        }

        // 发送心跳包
        try {
          const heartbeat = JSON.stringify({ type: 'heartbeat', timestamp: Date.now() });
          connection.ws.send(heartbeat);
          // 更新发送统计
          connection.messagesSent++;
        } catch (error) {
          console.error(`Failed to send heartbeat to ${connection.url}:`, error);
        }
      }
    }, this.config.heartbeatInterval);
  }

  /**
   * 停止心跳
   */
  private stopHeartbeat(connection: WSConnection) {
    if (connection.heartbeatTimer) {
      clearInterval(connection.heartbeatTimer);
      connection.heartbeatTimer = null;
    }
  }

  /**
   * 发送消息
   */
  send(sourceId: string, message: any): boolean {
    const connection = this.connections.get(sourceId);
    if (!connection || !connection.ws || connection.status !== 'connected') {
      console.error(`Cannot send message: connection ${sourceId} not available`);
      return false;
    }

    try {
      const messageStr = typeof message === 'string' ? message : JSON.stringify(message);
      connection.ws.send(messageStr);
      // 更新发送统计
      connection.messagesSent++;
      return true;
    } catch (error) {
      console.error(`Failed to send message to ${sourceId}:`, error);
      return false;
    }
  }

  /**
   * 断开指定连接
   */
  disconnect(sourceId: string) {
    const connection = this.connections.get(sourceId);
    if (!connection) return;

    this.stopHeartbeat(connection);

    if (connection.reconnectTimer) {
      clearTimeout(connection.reconnectTimer);
      connection.reconnectTimer = null;
    }

    if (connection.ws) {
      connection.ws.close(1000, 'Manual disconnect');
      connection.ws = null;
    }

    connection.status = 'disconnected';
    this.connections.delete(sourceId);
    this.messageHandlers.delete(sourceId);
  }

  /**
   * 断开所有连接
   */
  disconnectAll() {
    for (const [sourceId] of this.connections) {
      this.disconnect(sourceId);
    }
  }

  /**
   * 获取连接状态
   */
  getConnectionStatus(sourceId: string): string {
    const connection = this.connections.get(sourceId);
    return connection ? connection.status : 'disconnected';
  }

  /**
   * 获取所有连接状态
   */
  getAllConnectionStatus(): { [key: string]: string } {
    const status: { [key: string]: string } = {};
    for (const [id, connection] of this.connections) {
      status[id] = connection.status;
    }
    return status;
  }

  /**
   * 获取所有连接的详细信息
   */
  getAllConnections(): WSConnection[] {
    return Array.from(this.connections.values());
  }

  /**
   * 重连指定连接
   */
  reconnect(sourceId: string) {
    const connection = this.connections.get(sourceId);
    if (!connection) return;

    if (connection.ws) {
      connection.ws.close();
    }

    connection.reconnectAttempts = 0;
    this.doConnect(connection);
  }

  /**
   * 更新数据源配置
   */
  updateDataSources(dataSources: DataSource[]) {
    // 获取当前连接的ID列表
    const currentIds = new Set(this.connections.keys());
    const newIds = new Set(dataSources.filter((ds) => ds.enabled).map((ds) => ds.id));

    // 断开不再需要的连接
    for (const id of currentIds) {
      if (!newIds.has(id)) {
        this.disconnect(id);
      }
    }

    // 建立新的连接
    for (const dataSource of dataSources) {
      if (dataSource.enabled && !currentIds.has(dataSource.id)) {
        this.connect(dataSource);
      }
    }
  }
}

// 创建全局WebSocket管理器实例
export const wsManager = new WebSocketManager();
